<template>
  <div class="app-container">
    <el-form label-position="right" label-width="120px" :model="readerForm">
      <el-form-item label="数据库源：" prop="datasourceId">
        <el-select v-model="readerForm.datasourceId" filterable style="width: 30%" :loading="loading" @change="rDsChange">
          <el-option
            v-for="item in rDsList" :key="item.datasourceId" :label="item.datasourceGroup + '_' + item.datasourceName + '_' + item.datasourceType"
            :value="item.datasourceId" />
        </el-select>
      </el-form-item>
      <el-form-item v-show="datasourceType==='postgresql' || datasourceType==='oracle'" label="Schema：" prop="tableSchema">
        <el-select v-model="readerForm.tableSchema" filterable style="width: 30%" :loading="loading" @change="schemaChange">
          <el-option v-for="item in schemaList" :key="item" :label="item" :value="item" />
        </el-select>
      </el-form-item>
      <el-form-item label="数据库表名：" prop="tableName">
        <el-select v-model="readerForm.tableName" default-first-option filterable style="width: 30%" :loading="loading" @change="rTbChange">
          <el-option v-for="item in rTbList" :key="item" :label="item" :value="item" />
        </el-select>
      </el-form-item>
      <el-form-item label="SQL语句：">
        <el-input
          v-model="readerForm.querySql" :autosize="{ minRows: 3, maxRows: 20}" type="textarea" :rows="10" placeholder="sql查询，一般用于多表关联查询时才用"
          style="width: 50%" />
        <el-button v-if="showInitSql" type="primary" :loading="loading" @click.prevent="getReaderSql(readerForm.tableName)">内置sql</el-button>
        <el-button v-if="readerForm.querySql.trim() != ''" type="primary" :loading="loading" @click.prevent="getColumns('reader')">解析字段</el-button>
      </el-form-item>
      <el-form-item label="切分字段：">
        <el-input v-model="readerForm.splitPk" placeholder="仅支持整形数据切分，推荐使用主键字段【根据切分字段进行数据分片, 并发任务进行数据同步】" style="width: 40%" />
      </el-form-item>
      <!-- 采用内置sql, checkbox全部禁用 -->
      <el-form-item label="表所有字段：">
        <el-checkbox 
          v-model="readerForm.checkAll"
          :indeterminate="readerForm.isIndeterminate"
          @change="rHandleCheckAllChange"
        >全选
        </el-checkbox>
        <div style="margin: 15px 0;" />
        <el-checkbox-group v-model="readerForm.columns" @change="rHandleCheckedChange">
          <el-checkbox v-for="c in rColumnList" :key="c" :label="c">{{ c }}</el-checkbox>
        </el-checkbox-group>
      </el-form-item>
      <!-- <el-form-item v-if="readerForm.querySql == ''" label="where条件：" prop="where">
        <el-input v-model="readerForm.where" placeholder="where条件，不需要再加where" type="textarea" style="width: 40%"/>
      </el-form-item> -->
    </el-form>
  </div>
</template>

<script>
// import * as dsQueryApi from '@/api/job/metadata-query'
// import { list as jdbcDsList } from '@/api/job/datax-jdbcDatasource'

import { selectTables, selectSchema, selectColumns, selectTableInfo, selectColumnsByQuerySql } from '@data/api/data/datacollection'
import { search as datasourceList } from '@data/api/data/datasource'
import { useDataStore } from '@/store/modules/data'

// import Bus from '../busReader'

export default {
  name: 'RDBMSReader',
  data() {
    return {
      jdbcDsQuery: {},
      rDsList: [],
      rTbList: [],
      schemaList: [],
      rColumnList: [],
      ckColumnList: [],
      ckColumnConverList: [],
      priColumnList: [],
      loading: false,
      showInitSql: false,
      active: 1,
      customFields: '',
      customType: '',
      customValue: '',
      datasourceType: '',
      readerForm: {
        datasourceId: undefined,
        // jdbcUrl: undefined,
        tableName: '',
        columns: [],
        where: '',
        querySql: '',
        checkAll: false,
        isIndeterminate: true,
        splitPk: '',
        tableSchema: '',
        datasourceInfo: '',
        parseState: 0,
        initSql: 1
      },
      rules: {
        datasourceId: [{ required: true, message: '请选择数据源', trigger: 'change' }],
        tableName: [{ required: true, message: '请选择数据库表名', trigger: 'change' }],
        tableSchema: [{ required: true, message: '请选择Schema', trigger: 'change' }]
      }
    }
  },
  watch: {
    'readerForm.datasourceId': function (oldVal, newVal) {
      if (this.datasourceType === 'postgresql' || this.datasourceType === 'oracle') {
        this.getSchema()
      } else {
        this.getTables('rdbmsReader')
      }
    }
  },
  created() {
    this.getJdbcDs()
  },
  methods: {
    // 获取可用数据源
    getJdbcDs() {
      this.loading = true
      datasourceList(this.jdbcDsQuery).then(response => {
        const { list } = response.data
        this.rDsList = list //list.filter( item => item.jdbcUrl.includes('oracle'))
        this.loading = false
      })
    },
    // 获取表名
    getTables(type) {
      if (type === 'rdbmsReader') {
        console.log("=======:" + this.readerForm.datasourceId)
        if (this.readerForm.datasourceId) {
          let obj = {}
          if (this.datasourceType === 'postgresql' || this.datasourceType === 'oracle') {
            obj = {
              datasourceId: this.readerForm.datasourceId,
              tableSchema: this.readerForm.tableSchema
            }
          } else {
            obj = {
              datasourceId: this.readerForm.datasourceId
            }
          }
          // 组装
          this.loading = true
          selectTables(obj).then(response => {
            if (response) {
              this.loading = false
              this.rTbList = response.data
            }
          })
        }
      }
    },
    getSchema() {
      if (this.readerForm.datasourceId) {
        const obj = {
          datasourceId: this.readerForm.datasourceId
        }
        selectSchema(obj).then(response => {
          this.schemaList = response.data
        })
      }
    },
    // schema 切换
    schemaChange(e) {
      this.readerForm.tableSchema = e
      // 获取可用表
      this.getTables('rdbmsReader')
    },
    // reader 数据源切换
    rDsChange(e) {
      // 清空
      this.readerForm.tableName = ''
      this.readerForm.querySql = ''
      this.rColumnList = []
      this.showInitSql = false
      this.readerForm.tableSchema = ''

      this.readerForm.datasourceId = e
      this.loading = true
      this.rDsList.find((item) => {
        if (item.datasourceId === e) {
          this.datasourceType = item.datasourceType
          //by zwb：增加数据源信息，给 json-build 页面使用
          this.loading = false
          this.readerForm.datasourceInfo = item.datasourceGroup + '_' + item.datasourceName + '_' + item.datasourceType
        }
      })
      const dataStore = useDataStore()
      dataStore.setDataSourceId(e)
      // Bus.dataSourceId = e
      this.$emit('selectDataSource', this.datasourceType)
    },
    async getTableColumns() {
      //获取表所有字段名
      await selectColumns({'datasourceId':this.readerForm.datasourceId,'tableName':this.readerForm.tableName}).then(response => {
        this.rColumnList = response.data
        this.readerForm.columns = response.data
        this.readerForm.checkAll = true
        this.readerForm.isIndeterminate = false
      })
    },
    getColumnsByQuerySql() {
      const obj = {
        datasourceId: this.readerForm.datasourceId,
        querySql: this.readerForm.querySql
      }
      this.loading = true
      selectColumnsByQuerySql(obj).then(response => {
        this.rColumnList = response.data
        this.readerForm.columns = response.data
        this.readerForm.checkAll = true
        this.readerForm.isIndeterminate = false
        this.loading = false
        this.readerForm.parseState = 1
        this.$message.success('解析成功')
      }, reject => {
        this.loading = false
      })
    },
    // 获取表字段
    getColumns(type) {
      if (type === 'reader') {
        if (this.readerForm.querySql !== '') {
          this.getColumnsByQuerySql()
        } else {
          this.getTableColumns()
        }
      }
    },
    // 表切换
    rTbChange(t) {
      this.readerForm.querySql = ''
      this.readerForm.tableName = t
      this.rColumnList = []
      this.readerForm.columns = []
      this.getColumns('reader')
    },
    rHandleCheckAllChange(val) {
      this.readerForm.columns = val ? this.rColumnList : []
      this.readerForm.isIndeterminate = false
    },
    rHandleCheckedChange(value) {
      const checkedCount = value.length
      this.readerForm.checkAll = checkedCount === this.rColumnList.length
      this.readerForm.isIndeterminate = checkedCount > 0 && checkedCount < this.rColumnList.length
    },
    getData() {
      // const dataStore = useDataStore()
      // if (dataStore.getDataSourceId) {
      //   this.readerForm.datasourceId = dataStore.getDataSourceId
      // }
      return this.readerForm
    },
    resetForm() {
      this.readerForm = {
        datasourceId: undefined,
        tableName: '',
        columns: [],
        where: '',
        querySql: '',
        checkAll: false,
        isIndeterminate: true,
        splitPk: '',
        tableSchema: ''
      }
    },
    //by zwb：适用于，中间表记录没有标识 到底是新增、还是更新、还是删除的情况，通过MD5比对
    getReaderSql(tableName) {
      //1、获取选中的字段，默认全选，让有字段勾选改变的时候，这里也实时更新
      let columnField = this.ckColumnList.toString()  //这里取ck中字段   this.rColumnList.toString()  // todo 验证sql, 是所有字段md5, 还是非主键字段md5

      //binary_double 类型处理
      let columnConverField = this.ckColumnConverList.toString()

      if (columnField == '') {
        this.$notify({
          message: tableName + '表不存在，请联系管理员',
          type: 'warning',
          duration: 5000
        })
      }

      //2、排除 md5 字段
      if (columnField.indexOf(',ZBITI_MD5') != -1) {
        columnField = columnField.substring(0, columnField.lastIndexOf(',ZBITI_MD5'))
        columnConverField = columnConverField.substring(0, columnConverField.lastIndexOf(',ZBITI_MD5'))
      }
      if (columnField.indexOf(',ZBITI_SIGN') != -1) {
        columnField = columnField.substring(0, columnField.lastIndexOf(',ZBITI_SIGN'))
        columnConverField = columnConverField.substring(0, columnConverField.lastIndexOf(',ZBITI_SIGN'))
      }
      if (columnField.indexOf(',ZBITI_VERSION') != -1) {
        columnField = columnField.substring(0, columnField.lastIndexOf(',ZBITI_VERSION'))
        columnConverField = columnConverField.substring(0, columnConverField.lastIndexOf(',ZBITI_VERSION'))
      }


      //获取 构建reader 中的 数据库源 信息， 截取最后的数据源信息
      let datasourceInfo = this.readerForm.datasourceInfo
      datasourceInfo = datasourceInfo.substring(datasourceInfo.lastIndexOf("_") + 1)

      if (columnField != '') {
        if (datasourceInfo == 'oracle') {
          this.readerForm.querySql = 'SELECT ' + columnConverField + ',F_MD5(' + columnField.replaceAll(',', '||') + ') AS ZBITI_MD5 FROM ' + tableName
        } else if (datasourceInfo == 'mysql') {
          this.readerForm.querySql = 'SELECT ' + columnConverField + ',UPPER(MD5(CONCAT(' + columnField + '))) AS ZBITI_MD5 FROM ' + tableName
        } else if (datasourceInfo == 'clickhouse') {
          this.readerForm.querySql = 'SELECT ' + columnConverField + ',hex(MD5(CONCAT(' + columnField + '))) AS ZBITI_MD5 FROM ' + tableName
        } else {
          this.readerForm.querySql = ''
        }
      }

      //更新状态：表示内置sql按钮已经操作过
      this.readerForm.initSql = 1
    }
  }
}
</script>
